﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ais_editor
{
    public class DataEditor
    {
        private List<Ship> shipList;
        private string[] fieldNames;

        public string[] FieldNames { get => fieldNames; set => fieldNames = value; }
        public List<Ship> ShipList { get => shipList; set => shipList = value; }

        /// <summary>
        /// 
        /// ShipName,CallSign,IMO,MMSI,ShipTypeCN,
        //  ShipTypeEN,NavStatusCN,NavStatusEN,Length,Width,
        //  Draught,Heading,Course,Speed,Lon,
        //  Lat,Rot,Dest,ETA,Receivedtime（UTC+8）,
        //  UnixTime,Lon_d,Lat_d
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public List<Ship> LoadFromCSVFile(string filePath)
        {
            shipList = new List<Ship>();
            using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath, Encoding.GetEncoding("GB2312")))
            {
                int id = 0;
                string headerline = reader.ReadLine();//首行
                FieldNames = headerline.Split(',');

                string line = "";
                while ((line = reader.ReadLine()) != null)
                {
                    string[] fieldValues = line.Split(',');
                    var ship = new Ship();
                    ship.ShipName = fieldValues[0].Trim();
                    ship.MMSI = fieldValues[3].Trim();
                    ship.Lon = Convert.ToDouble(fieldValues[21].Trim());
                    ship.Lat = Convert.ToDouble(fieldValues[22].Trim());
                    ship.Heading = Convert.ToDouble(fieldValues[11].Trim());
                    //ship.Direction = Convert.ToDouble(data[4].Trim());
                    ship.Time = Convert.ToDateTime(fieldValues[19].Trim());

                    Dictionary<string, string> fields = new Dictionary<string, string>();
                    for (int i = 0; i < FieldNames.Length; i++)
                    {
                        fields.Add(FieldNames[i], fieldValues[i]);

                    }
                    ship.Values = fields;
                    shipList.Add(ship);
                }
            }
            return shipList;
        }

        public List<string> GetShipNames()
        {
            return shipList.Select(ele => ele.ShipName).Distinct().ToList();
        }
        //public void SaveToCSV(List<Ship> shipList, string filePath)
        //{
        //    try
        //    {
        //        using (StreamWriter sw = new StreamWriter(filePath))
        //        {
        //            string header = string.Join(",", new string[] {
        //                "Id",
        //                "Name",
        //                "Time",
        //                "Lon",
        //                "Lat",
        //                "Speed",
        //                "PLon",
        //                "PLat",
        //                "LineId",
        //                "LineName",
        //                "HDistance",
        //                "VDistance"
        //            });
        //            sw.WriteLine(header);
        //            foreach (var item in shipList)
        //            {
        //                //if (item.PLon < 111.131171 || item.Lon > 111.348019)
        //                //    continue;
        //                sw.WriteLine(item.ToString());
        //            }
        //        }
        //        MessageBox.Show("数据已成功导出到文件！");
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //}

        public void Test()
        {
            var tt = ShipList.GroupBy(ele => ele.ShipName);
            // 使用Newtonsoft.Json库进行序列化
            string json2 = JsonConvert.SerializeObject(tt);
            Console.WriteLine(json2.Length);
            Console.WriteLine(json2);


        }
        public void SaveToJson(List<Ship> shipList, string filePath)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    var tt = ShipList.Select(ele => new
                    {
                        lat = ele.Lat,
                        lng = ele.Lon,
                        time = ele.Time.Subtract(new DateTime(1970, 1, 1)).TotalSeconds,
                        dir = new Random().Next(0, 360),
                        heading = new Random().Next(0, 360),
                        //info = ele.Values,
                        Name = ele.ShipName
                    }).GroupBy(ele => ele.Name);
                    string json2 = JsonConvert.SerializeObject(tt);
                    sw.WriteLine(json2.ToString());

                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

    }
}
